import { CE, type Viewer } from "vendor/components/pro-cesium";

type EventType = "mouseMove" | "click";
type CallbackFN = (e: any) => void;

export class MapEventBus{
    private readonly viewer: Viewer;
    private eventTypeToFnList: {
        mouseMove: CallbackFN[],
        click: CallbackFN[],
    } = {
        mouseMove: [],
        click: [],
    };

    constructor(viewer: Viewer) {
        this.viewer = viewer;
        this.initListenEvent();
    }

    /**
     * 监听事件
     */
    on = (eventType: EventType, fn: CallbackFN) => {
        if (!this.eventTypeToFnList[eventType]) this.eventTypeToFnList[eventType] = [];
        this.eventTypeToFnList[eventType].push(fn);
    }

    /**
     * 解绑事件
     */
    off = (eventType: EventType, fn: CallbackFN) => {
        if (this.eventTypeToFnList[eventType]){
            const index = this.eventTypeToFnList[eventType].indexOf(fn);
            this.eventTypeToFnList[eventType].splice(index, 1)
        }
    }

    /**
     * 销毁
     */
    destroy = () => {
        this.viewer.off(CE.ViewerEventType.MOUSE_MOVE, this.handleMouseMove);
        this.viewer.off(CE.ViewerEventType.CLICK, this.handleClick);
    }

    /**
     * 初始化监听事件
     */
    private initListenEvent = () => {
        this.viewer.on(CE.ViewerEventType.MOUSE_MOVE, this.handleMouseMove);
        this.viewer.on(CE.ViewerEventType.CLICK, this.handleClick);
    }

    /**
     * 处理鼠标移动
     */
    private handleMouseMove = (e: any) => {
        this.eventTypeToFnList.mouseMove.forEach(fn => fn(e));
    }

    /**
     * 处理鼠标移动
     */
    private handleClick = (e: any) => {
        this.eventTypeToFnList.click.forEach(fn => fn(e));
    }
}